﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using Agnes.Core;
using Caliburn.Micro;
using Microsoft.Win32;
using System.Windows.Forms;
using System.IO;
using DevExpress.Xpf.RichEdit;
using DevExpress.XtraRichEdit.API.Native;
using DevExpress.XtraRichEdit;
using System.Windows;
using System.Windows.Controls;

namespace Agnes.MyDocsLib
{
    /// <summary>
    /// 导入文章命令
    /// </summary>
    public class ImportCmd
    {
        private static ImportCmd _instance;

        /// <summary>
        /// 返回唯一实例
        /// </summary>
        public static ImportCmd Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ImportCmd();
                }
                return _instance;
            }
        }

        private RoutedCommand _requery;

        /// <summary>
        /// 是否能执行
        /// </summary>
        public bool CanExcuted { get; set; }

        ImportCmd()
        {
            CanExcuted = true;
            _requery = new RoutedCommand("Article Edit Cmd", typeof(ImportCmd));
        }

        /// <summary>
        /// 路由命令
        /// </summary>
        public static RoutedCommand Requery
        {
            get
            {
                return Instance._requery;
            }
        }


        /// <summary>
        /// 执行代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Excuted(object sender, ExecutedRoutedEventArgs e)
        {
            Window win = new Window();
            win.Content = "导入中......";
            win.WindowStyle = WindowStyle.None;
            win.ShowInTaskbar = false;
            win.BorderThickness = new Thickness(0.5);
            
            win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            win.Topmost = true;

            win.SizeToContent = SizeToContent.WidthAndHeight;
            try
            {
                FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
                folderBrowserDialog.ShowNewFolderButton = false;
                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    Catalog cata = Catalog.CreateAsChild();
                    cata.Title = new DirectoryInfo(folderBrowserDialog.SelectedPath).Name;
                    int count = 0;
                    win.Show();
                    ImportFile(folderBrowserDialog.SelectedPath, cata, ref count);
                    System.Windows.MessageBox.Show("导入成功：导入了 " + count + " 个文档");
                    MyDocsLibManager.Instance.ArticleManager.Roots.Add(cata);
                    MyDocsLibManager.Instance.ArticleManager.Save();
                }
            }
            catch (Exception ex)
            {
                AgnesServiceManager.LogServ.Error("MyDocsLib--导入文档集失败，原因：" + ex.Message);
            }
            finally
            {
                win.Content = null;
                win.Close();
            }
        }

        private void ImportFile(string path, Catalog catalog,ref int count)
        {
            List<string> dirs = new List<string>(Directory.GetDirectories(path));
            List<string> files = new List<string>(Directory.GetFiles(path, "*.doc", SearchOption.TopDirectoryOnly));

            foreach (string file in files)
            {  
                Article article = Article.CreateAsChild();
                article.Title = new FileInfo(file).Name;
                article.ParentCatalog = catalog;

                try
                {
                    if (file.EndsWith("docx"))
                    {
                        RichEditControl richEditControl = new RichEditControl();
                        richEditControl.Document.LoadDocument(file, DocumentFormat.OpenXml);
                        richEditControl.Document.SaveDocument(article.DocumentPath, DocumentFormat.Mht);
                        count++;
                        catalog.Childs.Add(article);
                        AgnesServiceManager.LogServ.Debug("MyDocsLib--导入文档：" + file + " 成功");
                    }
                    else if (file.EndsWith("doc"))
                    {
                        RichEditControl richEditControl = new RichEditControl();
                        richEditControl.Document.LoadDocument(file, DocumentFormat.Doc);
                        richEditControl.Document.SaveDocument(article.DocumentPath, DocumentFormat.Mht);
                        catalog.Childs.Add(article);
                        count++;
                        AgnesServiceManager.LogServ.Debug("MyDocsLib--导入文档：" + file + " 成功");
                    }
                }
                catch (Exception ex)
                {
                    //AgnesServiceManager.LogServ.Error("MyDocsLib--导入文档：" + file + "失败！" + "原因：" + ex.Message);
                }
            }
            
            foreach (string dir in dirs)
            {
                Catalog cata = Catalog.CreateAsChild();
                cata.ParentCatalog = catalog;
                catalog.Childs.Add(cata);

                cata.Title = new DirectoryInfo(dir).Name;
                ImportFile(dir, cata, ref count);
            }
        }

        /// <summary>
        /// 判断是否能执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void CanExcute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (AgnesServiceManager.AgnesSlnService.CurrentSln == null)
            {
                e.CanExecute = false;
            }
            else
            {
                e.CanExecute = true;
            }
        }
    }
}
